import { createWebHashHistory, createRouter } from "vue-router";
import store from '../state'
import component from "element-plus/es/components/tree-select/src/tree-select-option.mjs";

const routes = [
    {
        path: "/",
        redirect: "/login"
    },
    {
        path: '/:catchAll(.*)',
        component: () => import('../view/error/404.vue'),
        name: 'NotFound'
    },
    {
        path: "/login",
        component: () => import('../view/Login.vue')
    },
]

//创建路由实例
let router = createRouter({
    history: createWebHashHistory(),//路由方式 createWebHistory() 或 createWebHashHistory()
    routes: routes//注册路由规则
});


/**
 * 初始路由信息
 */
function initRouter() {
    let appendRoute = {};
    appendRoute.path = "/layout";
    appendRoute.name = "layout";
    appendRoute.component = () => import(`../view/layout/Layout.vue`);
    appendRoute.children = [];
    //从store获取当前的权限信息
    let menus = store.getters.menus;

    // 首先把你需要动态路由的组件地址全部获取
    let modules = import.meta.glob('../view/**/*.vue')

    for (let menu of menus) {
        //console.log(menu)
        menu.children.forEach((temp, index) => {
            let item = {};
            //将从store中获取的路由路径对应组件名称 /nodelist/approveNode
            let vueName = temp.path
            let indexN = temp.path.lastIndexOf("/") + 1
            vueName = vueName.substr(0, indexN) + vueName.substring(indexN).charAt(0).toUpperCase() + vueName.substring(indexN + 1)
            // item.component = () => import(`../view${vueName}.vue`);  // ../view/nodelist/ApproveNode
            item.component = modules[`../view${vueName}.vue`]
            item.path = temp.path;
            item.name = temp.title;

            // 为公告管理添加子路由
            if (temp.path === '/noticeManagement/manageNotice') {
                item.redirect = '/noticeManagement/manageNotice/draft';  // 在这里设置redirect
                item.children = [
                    {
                        path: 'draft',
                        name: 'DraftNotice',
                        component: () => import('../view/noticeManagement/DraftNotice.vue')
                    },
                    {
                        path: 'published',
                        name: 'PublishedNotice',
                        component: () => import('../view/noticeManagement/PublishedNotice.vue')
                    }
                ]
            }

            appendRoute.children.push(item);
        });
    }
    //添加菜单外的AddItemToLevel、ServiceBuy、UserToCustomerService路由
    //appendRoute.children.push({path:"/nurse/addItemToLevel",component:() => import('@/views/nurse/AddItemToLevel.vue')})

    router.addRoute(appendRoute);
}

//路由守卫
router.beforeEach((to, from, next) => {
    // 首次加载时初始化路由
    if (router.getRoutes().length === 3 &&
        store.getters.menus &&
        store.getters.menus.length > 0) {
        initRouter();
        next({ path: to.path });
        return;
    }

    // 获取当前完整路径
    const currentPath = to.fullPath;
    const menus = store.getters.menus;
    let currentMenu = null;

    // 特殊处理公告管理的子路由
    if (currentPath.startsWith('/noticeManagement/manageNotice')) {
        // 查找公告管理的父级菜单项
        const noticeMenu = menus.find(menu => menu.menusIndex === "5");
        if (noticeMenu) {
            currentMenu = noticeMenu.children.find(
                child => child.path === '/noticeManagement/manageNotice'
            );

            // 如果是子路由，添加到tabs的是父级路径
            if (currentMenu) {
                store.commit("addTab", {
                    ...currentMenu,
                    path: '/noticeManagement/manageNotice' // 强制使用父路径
                });
            }
        }
    }
    // 正常处理其他路由
    else {
        // 遍历菜单查找匹配项
        outerLoop:
        for (const menu of menus) {
            for (const child of menu.children) {
                if (child.path === currentPath) {
                    currentMenu = child;
                    break outerLoop;
                }
            }
        }

        // 添加到tabs
        if (currentMenu) {
            store.commit("addTab", currentMenu);
        }
    }

    // 放行路由
    next();
});

export default router;